package com.czkevin.guicontrolsapi.controls;

import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;

public class ProgressBarControl extends GUIControl {

  private static final ItemStack DISPLAY_VALID = new ItemStack(Material.LIME_STAINED_GLASS_PANE);
  private static final ItemStack DISPLAY_NOT_VALID = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);

  public static final int HORIZONTAL = 0;
  public static final int VERTICAL = 1;

  private final int direction;
  private final int length;
  private float maxValue;
  private float value;

  private final ItemStack displayValid;
  private final ItemStack displayNotValid;

  public ProgressBarControl(int direction, int length) {
    this(direction, length, 100f, 50f, DISPLAY_VALID, DISPLAY_NOT_VALID);
  }

  public ProgressBarControl(int direction, int length, float maxValue, float value) {
    this(direction, length, maxValue, value, DISPLAY_VALID, DISPLAY_NOT_VALID);
  }

  public ProgressBarControl(int direction, int length, float maxValue, float value, ItemStack displayValid, ItemStack displayNotValid) {
    if(direction != HORIZONTAL && direction != VERTICAL) throw new IllegalArgumentException("invalid direction");
    this.direction = direction;
    this.length = length;
    this.maxValue = maxValue;
    this.value = value;
    this.displayValid = displayValid;
    this.displayNotValid = displayNotValid;
  }

  public float getMaxValue() {
    return maxValue;
  }

  public void setMaxValue(float maxValue) {
    this.maxValue = maxValue;
  }

  public float getValue() {
    return value;
  }

  public void setValue(float value) {
    this.value = value;
  }

  private float calculatePercentage() {
    return value / maxValue;
  }

  @Override
  public void onClick(InventoryClickEvent inventoryClickEvent, int i, int i1) { }

  @Override
  public int getWidth() {
    return direction == HORIZONTAL ? length : 1;
  }

  @Override
  public int getHeight() {
    return direction == VERTICAL ? length : 1;
  }

  @Override
  public void onRender(boolean b) {
    final float perc = calculatePercentage();
    for(int i = 0; i < length; i++) {
      float p = ((float) i) / length;
      getWindow().setDisplayItemAt(
          getX() + (direction == HORIZONTAL ? i : 0),
          getY() + (direction == VERTICAL ? (length - 1 - i) : 0),
          p < perc ? displayValid : displayNotValid
      );
    }
  }

}
